package com.jay.tools.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

@SuppressLint("SimpleDateFormat")
public class TimeUtil {

    public static final String FORMAT_FULL_MSEC = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_HOUR = "HH:mm:ss";
    public static final String FORMAT_YEAR = "yyyy-MM-dd";

    private static final long ONE_MINUTE = 60; // 单位秒
    private static final long ONE_HOUR = 3600;// 单位秒
    private static final long ONE_DAY = 86400;// 单位秒

    public static String fromatNow() {
        return getNowTime(null, "yyyy-MM-dd HH:mm");
    }

    /**
     * @param millisecond
     * @param format      指定的格式化方式
     * @return
     * @des 获取当前时间
     */
    public static String getNowTime(Object millisecond, String format) {
        String formatStyle = "";
        SimpleDateFormat sf;
        if (millisecond == null) {
            millisecond = System.currentTimeMillis();
        }
        if (millisecond instanceof String) {
            throw new IllegalArgumentException("error param");
        }
        if (TextUtils.isEmpty(format)) {// 默认时间格式
            formatStyle = FORMAT_FULL;
            sf = new SimpleDateFormat(formatStyle, Locale.getDefault());
        } else if (format.equals("24")) {// 按24小时显示
            formatStyle = FORMAT_HOUR;
            sf = new SimpleDateFormat(formatStyle, Locale.SIMPLIFIED_CHINESE);
        } else {// 指定格式
            formatStyle = format;
            sf = new SimpleDateFormat(formatStyle, Locale.getDefault());
        }
        return sf.format(millisecond);
    }

    /**
     * 字符串时间转long
     *
     * @param time 20180612_144615
     * @return
     */
    public static Long convertTimeToLong(String time) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            date = sdf.parse(time);
            return date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 毫秒时间转换
     *
     * @param time     毫秒字符串 2018-06-12 14:46:15.403
     * @param withMsec 是否毫秒
     * @return
     */
    public static Long msec2Long(String time, boolean withMsec) {
        if (time.contains(".") && !withMsec) {
            time = time.substring(0, time.lastIndexOf("."));
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(withMsec ? FORMAT_FULL_MSEC : FORMAT_FULL);
            Date date = sdf.parse(time);
            return date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 本月的第几周
     */
    public static int getWeekOfMonth() {
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.WEEK_OF_MONTH);
        return week - 1;
    }

    /**
     * 本年的第几周
     */
    public static int getWeedOfYear() {
        try {
            SimpleDateFormat df = new SimpleDateFormat(FORMAT_YEAR);
            Calendar cal = Calendar.getInstance();
            // 这一句必须要设置，否则美国认为第一天是周日，而我国认为是周一，对计算当期日期是第几周会有错误
            cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
            cal.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天
            cal.setTime(df.parse(getNowTime(new Date(), FORMAT_YEAR)));
            cal.set(Calendar.DATE, getDayOfWeek());
            return cal.get(Calendar.WEEK_OF_YEAR);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 根据0或1返回上午11:40，下午17:40的时间戳
     *
     * @param timeSetion 上午：0 下午：1
     */
    public static long getPointTime(int timeSetion) {
        Calendar c = Calendar.getInstance();
        int hour = timeSetion == 0 ? 11 : 17;
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), hour, 40, 0);
        Date d = c.getTime();
        return d.getTime();
    }

    /**
     * 根据索引获取指定的日期
     *
     * @param index 索引从 0 - 6, 0表示当天
     * @return 2018-08-03
     */
    public static String getDateByIndex(int index) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, index);
        Date d = c.getTime();
        return new SimpleDateFormat(FORMAT_YEAR).format(d);
    }

    /**
     * 根据索引获取指定的星期
     *
     * @param index 索引从0 - 6 0表示当天
     * @return
     */
    public static String getDayOfWeekByIndex(int index) {
        String weekOfDay = "";
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, index);
        c.setTime(c.getTime());

        int w = c.get(Calendar.DAY_OF_WEEK);
        switch (w) {
            case 1:
                weekOfDay = "周日";
                break;
            case 2:
                weekOfDay = "周一";
                break;
            case 3:
                weekOfDay = "周二";
                break;
            case 4:
                weekOfDay = "周三";
                break;
            case 5:
                weekOfDay = "周四";
                break;
            case 6:
                weekOfDay = "周五";
                break;
            case 7:
                weekOfDay = "周六";
                break;
        }
        if (index == 0) {
            weekOfDay = "今天";
        } else if (index == 1) {
            weekOfDay = "明天";
        }
        return weekOfDay;
    }

    /**
     * 获取星期几
     */
    public static int getDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        if (day == 1) {
            day = 7;
        } else {
            day = day - 1;
        }
        return day;
    }

    /**
     * 显示当天日期，星期<br>
     * 格式：2015-11-12 周日
     */
    public static String StringDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        int mYear = c.get(Calendar.YEAR);// 获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1; // 获取当前月份
        int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
        int mWay = c.get(Calendar.DAY_OF_WEEK);// 获取星期
        String week = "";
        switch (mWay) {
            case 1:
                week = "日";
                break;
            case 2:
                week = "一";
                break;
            case 3:
                week = "二";
                break;
            case 4:
                week = "三";
                break;
            case 5:
                week = "四";
                break;
            case 6:
                week = "五";
                break;
            case 7:
                week = "六";
                break;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(mYear).append("-");
        sb.append(mMonth).append("-");
        sb.append(mDay).append(" ");
        sb.append("周").append(week);
        return sb.toString();
    }

    /**
     * 获取当前时间的年份
     */
    public static int getYear() {
        Calendar calendar = GregorianCalendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取当前时间的月份
     */
    public static int getMonth() {
        Calendar calendar = GregorianCalendar.getInstance();
        return calendar.get(Calendar.MONTH);
    }

    /**
     * 获取当前时间是哪天
     */
    public static int getDay() {
        Calendar calendar = GregorianCalendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 比较时间
     *
     * @param date1  时间1
     * @param date2  时间2
     * @param format 时间格式
     * @return 1:date1大于date2； -1:date1小于date2
     */
    public static int compareDate(String date1, String date2, String format) {
        DateFormat df = new SimpleDateFormat(format, Locale.getDefault());
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 时间加减
     *
     * @param day       2015-09-22
     * @param dayAddNum
     * @return
     */
    public static String timeAddSubtract(String day, int dayAddNum) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT_YEAR, Locale.getDefault());
        try {
            Date newDate = new Date(simpleDateFormat.parse(day).getTime() + dayAddNum * ONE_DAY);
            return simpleDateFormat.format(newDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取距离当前几天的时间，时间戳
     *
     * @param dayAddNum 正值表示今天后，负值表示距今前
     * @return 返回 2018-06-19 00:00:00 unix时间
     */
    public static long timeAddSubtract(int dayAddNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        long nowTime = calendar.getTime().getTime();
        long currentTime = 0l;
        if (dayAddNum < 0) {
            currentTime = nowTime - (Math.abs(dayAddNum) * ONE_DAY);
        } else {
            currentTime = nowTime + (dayAddNum * ONE_DAY);
        }
        return new Date(currentTime).getTime();
    }

    /**
     * 创建日期距离当前时间的差值时间，假设每月30天
     *
     * @param created 创建时间
     * @return 2天19小时14分钟28秒前
     */
    public static String getUploadtime(long created) {
        StringBuffer sb = new StringBuffer();
        int difference_seconds;
        int difference_minutes;
        int difference_hours;
        int difference_days;
        long curTime = System.currentTimeMillis();

        difference_days = (int) (((curTime / ONE_DAY) % 30) - ((created / ONE_DAY) % 30));
        if (difference_days > 0) {
            sb.append(difference_days + "天");
        }
        difference_hours = (int) (((curTime / ONE_HOUR) % 24) - ((created / ONE_HOUR) % 24));
        if (difference_hours > 0) {
            sb.append(difference_hours + "小时");
        }
        difference_minutes = (int) (((curTime / ONE_MINUTE) % ONE_MINUTE - ((created / ONE_MINUTE) % ONE_MINUTE)));
        if (difference_minutes > 0) {
            sb.append(difference_minutes + "分钟");
        }
        difference_seconds = (int) ((curTime % ONE_MINUTE) - (created % ONE_MINUTE));
        if (difference_seconds > 0) {
            sb.append(difference_seconds + "秒");
        }
        return sb.append("前").toString();
    }

    /**
     * xx小时xx分xx秒
     */
    public static String getLong2Str(long time) {
        StringBuffer sb = new StringBuffer();
        int hour = (int) (time / ONE_HOUR);
        sb.append(hour).append("小时");
        if (hour > 0) {
            time = time - hour * ONE_HOUR;
        }
        int minute = (int) (time / ONE_MINUTE);
        int sec = (int) (time % ONE_MINUTE);
        sb.append(minute).append("分");
        sb.append(sec).append("秒");
        return sb.toString();
    }


    /**
     * xx天xx时xx分
     */
    public static String getStr2Str(String lasttime) {
        StringBuffer sb = new StringBuffer();
        if (!TextUtils.isEmpty(lasttime)) {
            int time = Integer.parseInt(lasttime);
            int day = (int) (time / (ONE_DAY));
            sb.append(day).append("天");
            if (day > 0) {
                time = (int) (time - day * ONE_DAY);
            }
            int hour = (int) (time / ONE_HOUR);
            sb.append(hour).append("时");
            if (hour > 0) {
                time = (int) (time - hour * ONE_HOUR);
            }
            int minute = (int) (time / ONE_MINUTE);
            sb.append(minute).append("分");
        }
        return sb.toString();
    }
}
